package api

import (
	"net/http"

	"example.com/example/dao"
	"example.com/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configTemplateRouter(router *httprouter.Router) {
	router.GET("/template", GetAllTemplate)
	router.POST("/template", AddTemplate)
	router.GET("/template/:argId", GetTemplate)
	router.PUT("/template/:argId", UpdateTemplate)
	router.DELETE("/template/:argId", DeleteTemplate)
}

func configGinTemplateRouter(router gin.IRoutes) {
	router.GET("/template", ConverHttprouterToGin(GetAllTemplate))
	router.POST("/template", ConverHttprouterToGin(AddTemplate))
	router.GET("/template/:argId", ConverHttprouterToGin(GetTemplate))
	router.PUT("/template/:argId", ConverHttprouterToGin(UpdateTemplate))
	router.DELETE("/template/:argId", ConverHttprouterToGin(DeleteTemplate))
}

// GetAllTemplate is a function to get a slice of record(s) from template table in the custom_process database
// @Summary Get list of Template
// @Tags Template
// @Description GetAllTemplate is a handler to get a slice of record(s) from template table in the custom_process database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.Template}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /template [get]
// http "http://localhost:8080/template?page=0&pagesize=20" X-Api-User:user123
func GetAllTemplate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "template", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllTemplate(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetTemplate is a function to get a single record from the template table in the custom_process database
// @Summary Get record from table Template by  argId
// @Tags Template
// @ID argId
// @Description GetTemplate is a function to get a single record from the template table in the custom_process database
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 200 {object} model.Template
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /template/{argId} [get]
// http "http://localhost:8080/template/1" X-Api-User:user123
func GetTemplate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "template", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetTemplate(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddTemplate add to add a single record to template table in the custom_process database
// @Summary Add an record to template table
// @Description add to add a single record to template table in the custom_process database
// @Tags Template
// @Accept  json
// @Produce  json
// @Param Template body model.Template true "Add Template"
// @Success 200 {object} model.Template
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /template [post]
// echo '{"id": 12,"name": "KwJawCeihiouXZMBtkdPOjIpO","create_time": "2104-01-20T23:43:01.067338471+08:00","update_time": "2081-04-09T13:50:44.296663193+08:00"}' | http POST "http://localhost:8080/template" X-Api-User:user123
func AddTemplate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	template := &model.Template{}

	if err := readJSON(r, template); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := template.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	template.Prepare()

	if err := template.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "template", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	template, _, err = dao.AddTemplate(ctx, template)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, template)
}

// UpdateTemplate Update a single record from template table in the custom_process database
// @Summary Update an record in table template
// @Description Update a single record from template table in the custom_process database
// @Tags Template
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Param  Template body model.Template true "Update Template record"
// @Success 200 {object} model.Template
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /template/{argId} [put]
// echo '{"id": 12,"name": "KwJawCeihiouXZMBtkdPOjIpO","create_time": "2104-01-20T23:43:01.067338471+08:00","update_time": "2081-04-09T13:50:44.296663193+08:00"}' | http PUT "http://localhost:8080/template/1"  X-Api-User:user123
func UpdateTemplate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	template := &model.Template{}
	if err := readJSON(r, template); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := template.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	template.Prepare()

	if err := template.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "template", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	template, _, err = dao.UpdateTemplate(ctx,
		argId,
		template)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, template)
}

// DeleteTemplate Delete a single record from template table in the custom_process database
// @Summary Delete a record from template
// @Description Delete a single record from template table in the custom_process database
// @Tags Template
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 204 {object} model.Template
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /template/{argId} [delete]
// http DELETE "http://localhost:8080/template/1" X-Api-User:user123
func DeleteTemplate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "template", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeleteTemplate(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
